<template>
  <div class="container">
    <el-card>
      <div class="title" slot="header" v-if="this.$route.query.id">
        试题录入
      </div>
      <div class="title" slot="header" v-else>试题录入</div>
      <el-form :model="form" label-width="100px" :rules="rules" ref="form">
        <!-- 学科 -->

        <el-form-item label="学科：" prop="userSubject">
          <el-select
            style="width: 400px"
            v-model="form.userSubject"
            placeholder="请选择"
            @change="changeSub"
          >
            <el-option
              v-for="(item, index) in form.subjects"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="usercatalog">
          <el-select
            style="width: 400px"
            v-model="form.usercatalog"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in form.catalog"
              :key="index"
              :label="item.directoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" prop="usercompany">
          <el-select
            style="width: 400px"
            v-model="form.usercompany"
            placeholder="请选择"
          >
            <el-option
              v-for="item in form.company"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" prop="usercitys">
          <el-select
            style="width: 190px"
            v-model="form.usercitys"
            placeholder="请选择"
            @change="changecity"
          >
            <el-option
              v-for="(item, index) in form.citys"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select
            style="width: 200px; margin-left: 10px"
            v-model="form.usercitys2"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in form.citys2"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="userDirection">
          <el-select
            style="width: 400px"
            v-model="form.userDirection"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in form.directions"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio :label="1" value="1">单选</el-radio>
            <el-radio :label="2" value="2">多选</el-radio>
            <el-radio :label="3" value="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="userdifficulty">
          <el-radio-group v-model="form.userdifficulty">
            <el-radio :label="1" value="1">简单</el-radio>
            <el-radio :label="2" value="2">一般</el-radio>
            <el-radio :label="3" value="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干：" prop="userTag">
          <quillEditor
            class="editor"
            v-model="form.content1"
            :options="editorOption"
          ></quillEditor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项：" v-if="form.userType !== 3">
          <!-- 单选框 -->
          <el-radio-group
            v-model="form.userCheck"
            v-if="form.userType === 1"
            @change="hradioChange"
          >
            <div class="col" v-for="(item, index) in options" :key="index">
              <div class="row">
                <el-radio :label="item.code"></el-radio>
                <el-input v-model="item.title" style="width: 230px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :http-request="beforeAvatarUpload"
                >
                  <img
                    v-if="item.imageUrl"
                    :src="item.imageUrl"
                    class="avatar"
                  />
                  <i v-else class="avater-text">上传图片</i>
                </el-upload>
              </div>
            </div>
          </el-radio-group>
          <!-- 复选框 -->
          <el-checkbox-group
            v-model="form.userCheckList"
            v-else-if="form.userType === 2"
            @change="hcheckboxChange"
          >
            <div class="col" v-for="(item, index) in options" :key="index">
              <div class="row">
                <!-- a 选项部分 -->
                <el-checkbox
                  :label="item.code"
                  v-if="form.userType === 2"
                ></el-checkbox>
                <!-- <el-radio :label="item.code"  v-else-if="form.userType === '单选'"></el-radio> -->
                <el-input
                  v-model="item.title"
                  style="width: 300px; margin-left: 30px"
                ></el-input>
                <el-upload
                  action=""
                  class="avatar-uploader"
                  :http-request="beforeAvatarUpload"
                  :show-file-list="false"
                >
                  <img
                    v-if="item.imageUrl"
                    :src="item.imageUrl"
                    class="avatar"
                  />
                  <i v-else class="avater-text">上传图片</i>
                </el-upload>
              </div>
            </div>
          </el-checkbox-group>
          <!-- 添加按钮部分 -->
          <div class="row">
            <el-button
              type="danger"
              :disabled="form.userType === 1 ? true : false"
              @click="haddoption"
              >+增加选项与答案</el-button
            >
          </div>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input v-model="form.inputVideo"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item
          label="答案解析："
          v-model="form.userAnswer"
          prop="userAnswer"
        >
          <quillEditor
            class="editor"
            v-model="form.userAnswer"
            :options="editorOption"
          ></quillEditor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：">
          <el-input
            style="width: 500px"
            v-model="form.remarks"
            type="textarea"
          ></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select
            style="width: 400px"
            v-model="form.userTag"
            placeholder="请选择试题标签"
            multiple
            filterable
            allow-create
            
          >
            <el-option
              v-for="item in form.listTag"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 确认提交 -->
        <el-form-item>
          
          <el-button type="success" @click="confirmRevise" v-if="this.$route.query.id">确认修改</el-button>
          <el-button type="primary" @click="confirmSubmit" v-else>确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 富文本编辑器
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 学科接口
import { simple } from '@/api/hmmm/subjects.js'
// 学科目录简单列表
import { simple as simpleDir } from '@/api/hmmm/directorys.js'
// 目录列表
import { list as simpleList } from '@/api/hmmm/directorys'
// 企业接口
import { list } from '@/api/hmmm/companys.js'
// 城市接口
import { provinces } from '@/api/hmmm/citys.js'
// 城市下区接口
import { citys } from '@/api/hmmm/citys.js'
// 方向
import { direction } from '@/api/hmmm/constants.js'

// 试题标签
import { list as listTag } from '@/api/hmmm/tags.js'

// 基础题库
import { add, update, detail } from '@/api/hmmm/questions.js'
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      form: {
        subjects: [],
        catalog: [],
        company: [],
        citys: [],
        citys2: [],
        directions: [],
        listTag: [],


        // 双向绑定 

        userSubject: null, // 学科列表
        usercatalog: '', // 目录列表
        usercompany: '',  // 企业列表
        usercitys: '', // 城市列表
        usercitys2: '',
        userDirection: '', // 方向列表
        userType: 1, //题型选择
        userdifficulty: 1, //题型难度
        content1: '', // 富文本编辑器1
        userCheck: '', // 选项 1
        userCheckList: '', // 选项2
        imageUrl: '', //  选项上传
        inputVideo: null, // 解析视频
        userAnswer: '', // 答案解析
        remarks: null, // 备注
        userTag: [], //试题标签
        userOptions: [],// 用户选择项数据
      },
      // 富文本编辑器工具菜单
      editorOption: {
        // 工具菜单栏配置
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['link', 'image', 'video'] // 链接、图片、视频
          ]
        }
      },
      // 定义表单规则
      rules: {
        userSubject: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        usercatalog: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        usercompany: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        usercitys: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        userDirection: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        userType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        userdifficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        userTag: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        userAnswer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }],
      },
      options: [
        {
          code: 'A:',
          isRight: 'false',
          title: '',
          imageUrl: ''
        },
        {
          isRight: 'false',
          title: '',
          code: 'B:',
          imageUrl: ''
        },
        {
          isRight: 'false',
          code: 'C:',
          title: '',
          imageUrl: ''
        },
        {
          isRight: 'false',
          code: 'D:',
          title: '',
          imageUrl: ''
        }
      ],
    }
  },
  // 监听表单列表的切换
  watch: {
    // 监听 学科列表变化
    'form.userSubject': {
      async handler(newValue) {
        // console.log(newValue);
        // 获取 目录
        // const res = await simpleDir(newValue)
        // console.log(res.data)

        // 获取 标签
        const res1 = await listTag(newValue)

        // 将获取数据 赋值给目录
        // this.form.catalog = res.data
        // 将数据 赋值给试题标签
        this.form.listTag = res1.data.items
      },
      immediate: true
    },
    // 监听 城市省份的变化
    'form.usercitys': {
      async handler(newValue) {
        // console.log(newValue);
        const res = await citys(newValue)
        // console.log(res);
        this.form.citys2 = res
      },
      immediate: true
    },
    // 监听路由变化
    $route(val) {
      console.log(val.query.id);
      if (val.query.id) {
        this.loadDetail()
      } else {
        this.$refs.form.resetFields()
      }
    },
  },
  created() {
    this.loadSubject()
    this.loadCompony()
    this.loadCitys()
    this.loadDirection()
    if (this.$route.query.id) {
      this.loadDetail()
    }

  },
  methods: {
    // 接口！！！！！！！！！！！！！！！！！！！！！
    // 获取 学科列表
    async loadSubject() {
      const res = await simple()
      // console.log(res.data)
      this.form.subjects = res.data
    },
    // 获取 企业列表
    async loadCompony() {
      const res = await list()
      // console.log(res.data.items);
      this.form.company = res.data.items

    },
    // 获取 所有的城市
    async loadCitys() {
      const res = await provinces()
      // console.log(res);
      this.form.citys = res
    },
    // 获取 方向列表
    loadDirection() {
      const res = direction
      // console.log(res);
      this.form.directions = res
    },

    //  方法！！！！！！！！！！！！！！！！
    // 图片上传
    async beforeAvatarUpload(fileObj) {
      console.log(fileObj);
      const fd = await new FormData()
      fd.append('photo', fileObj.file)
      this.$message.success('上传图片成功')
      // console.log(fd);
    },
    // 切换城市 后面区清空
    changecity() {
      this.form.usercitys2 = ''
    },
    // 切换学科，触发新的函数
    async changeSub(id) {
      this.form.userTag = ''
      this.form.usercatalog = ''
      // 调用 对应二级接口数据
      const { data: res } = await simpleList({ subjectID: id })
      // console.log(res.items);

      this.form.catalog = res.items
    },
    // 单选框表单组发生变化发生的事件
    hradioChange(val) {
      // 1. 获取点击的 code 的值
      this.form.userCheck = val
      // 2. 更改option数据项
      this.options.map((item, index) => {
        if (item.code === val) {
          // 更改当前项的 isRight的值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将 isRight为true 的数组 进行筛选出来
      // 将数组赋值给数据项
      this.form.userOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    //  多选框发生变化的时候 发生的事件
    hcheckboxChange(val) {
      this.form.userCheckList = val
      console.log(val)
      this.options.map((item, index) => {
        if (item.code) {
          // 更改当前的 isRight 值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将符合条件的数组筛选出来 赋值给数据线
      this.form.userOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    // 增加选项
    haddoption() {
      this.options.push({
        isRight: 'false',
        code: String.fromCharCode(this.options[this.options.length - 1].code.charCodeAt(0) + 1),
        title: '',
        imageUrl: ''
      })
    },
    // 基础题库列表的获取
    async loadDetail() {
      console.log(this.$route.query.id);
      try {
        const res = await detail({ id: this.$route.query.id })
        console.log(res)
        // 将获取的数据赋值给数据项
        this.form.userSubject = res.data.subjectID
        this.form.usercatalog = res.data.catalogID
        this.form.usercompany = res.data.enterpriseID
        this.form.usercitys = res.data.province
        this.form.usercitys2 = res.data.city
        this.form.userDirection = res.data.direction
        // 将后台返回的数据进行数据类型转换
        this.form.userType = Number(res.data.questionType)
        this.form.userdifficulty = Number(res.data.difficulty)
        // 题干
        this.form.content1 = res.data.question
        this.form.inputVideo = res.data.videoURL
        this.form.userAnswer = res.data.answer
        this.form.remarks = res.data.remarks // 备注
        this.form.userTag.push(res.data.tags)
        // 选项
        this.form.userOptions = res.data.options
        // 多选框的数据回流
        this.form.userCheckList = this.form.userOptions.filter(item => item.isRight === 1).map(item => item.code)
        // 单选框的数据回流
        this.form.userCheck = this.form.userOptions.filter(item => item.isRight === 1).map(item => item.code)[0]
      } catch (err) {
        console.log(err)
      }
    },
    // 数据验证，表单数据获取
    save() {
      // 表单验证
      this.$refs.form.validate(async val => {
        if (val) {
          // 严重通过,获取表单数据
          const data = {
            subjectID: this.form.userSubject,
            catalogID: this.form.usercatalog,
            enterpriseID: this.form.usercompany,
            city: this.form.usercitys,
            province: this.form.usercitys2,
            direction: this.form.userDirection,
            questionType: '' + this.form.userType,
            answer: this.form.userAnswer,
            difficulty: '' + this.form.userdifficulty,
            question: this.form.content1,
            options: this.form.userOptions,
            tags: toString(this.form.userTag)
          }
          console.log(data);
          // 发送请求 提交数据
          const res = await add(data)
          console.log(res);
          // 提示消息
          this.$message.success('录入成功')
          // 页面跳转
          this.$router.push('/questions/list')
        } else {
          this.$message.success('失败了')
        }
      })
    },
    // 点击提交
    confirmSubmit() {
      // 1.进行表单校验
      this.$refs.form.validate(val => {
        console.log(val);
        // 2.如果验证成功
        if (val) {
          this.save()
        }
      })
    },
    // 点击修改
    confirmRevise() {
      this.$refs.form.validate(val => {
        if (val) {
          this.revise()
        }
      })
    },
    // 请求数据 进行修改
    async revise() {
      //  console.log(1);
      if (this.form.inputVideo === null) {
        // console.log(1);
      }
      const data = {
        subjectID: this.form.userSubject,
        catalogID: this.form.usercatalog,
        enterpriseID: this.form.usercompany,
        city: this.form.usercitys,
        province: this.form.usercitys2,
        direction: this.form.userDirection,
        questionType: '' + this.form.userType,
        answer: this.form.userAnswer,
        difficulty: '' + this.form.userdifficulty,
        question: this.form.content1,
        options: this.form.userOptions,
        tags: toString(this.form.userTag),
        inputVideo: this.form.inputVideo === null ? '1' : this.form.inputVideo,
        remarks: this.form.remarks === null ? '1' : this.form.inputVideo,
      }
      console.log(data);
      const res = await update(data)
      // console.log(res);
      // 提示
      this.$message.success('试题修改成功')
      // 清空内容
      this.$refs.form.resetFields()
      // 跳转页面
      this.$route.push('/questions/list')
    }
  }
}
</script>

<style scoped>
.container {
  margin: 10px;
}

.title {
  height: 25px;
  padding: 10px;
}

.el-form {
  margin-left: 20px;
}
.editor {
  height: 200px;
  margin-bottom: 55px;
}

.el-input {
  width: 300px;
}

.el-radio-group {
  margin-top: 10px;
}
/* // 单选按钮 */
.el-radio-group .col {
  display: flex;
  flex-direction: column;
}

.el-radio,
.el-checkbox {
  margin-bottom: 30px;
  margin-right: 30px;
}

.el-form-item__label {
  margin-top: 100px;
}

/* 上传图片 */
.avatar-uploader .el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.avatar-uploader {
  text-align: center;
  margin-left: 10px;
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}

.avater-text {
  font-size: 14px;
  color: #8c939d;
}
</style>
